The implementation of Python for reading files by line [small file and large file reading]

  • 2020-05-12 02:48:15
  • OfStack

This article illustrates the implementation of Python for reading files by line. I will share it with you for your reference as follows:

Small files:


#coding=utf-8
#author: walker
#date: 2013-12-30
#function:  Read small files by line 
all_lines = []
try:
  file = open('txt.txt', 'r')
  all_lines = file.readlines()
except IOError as err:
  print('File error: ' + str(err))
finally:
  if 'file' in locals():
    file.close()
for line in all_lines:
  print(line)

Large files:


#coding=utf-8
#author: walker
#date: 2013-12-30
#function:  Read large files by line 
try:
  file = open('txt.txt', 'r')
  for line in file:
    print(line)
except IOError as err:
  print('File error: ' + str(err))
finally:
  if 'file' in locals():
    file.close()

More about Python related topics: interested readers to view this site "Python file and directory skills summary", "Python skills summary text file", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article is helpful to you Python programming.


Related articles: